<template>
  <div class="schedule-container">
    <a-calendar
      :fullscreen="true"
      @select="onSelectDate"
      @panelChange="onPanelChange"
      :value="moment(selectedDate || currentDate)"
      :mode="'month'"
    >
      <!-- 自定义日期单元格，显示排班信息 -->
      <template slot="dateCellRender" slot-scope="value">
        <div class="schedule-cell">
          <ul class="events">
            <li v-if="getListData(value).length > 0" v-for="item in getListData(value)" class="event pm-event">
              <a-badge :status="item.status === '1' ? 'success' : 'warning'"
                       :text="item.appointName + ' ' + item.appointCont + ' ' + item.appointTime"></a-badge>
            </li>
          </ul>
        </div>
      </template>

      <!-- 自定义头部，去除月/年切换按钮 -->
      <template slot="headerRender" slot-scope="{ value, type, onChange, onTypeChange }">
        <div style="padding: 30px">
          <a-row type="flex" justify="space-between" align="middle">
            <a-col>
              <a-button
                type="primary"
                @click="handleScheduleAction"
              >
                {{ hasScheduleForSelectedDate ? '编辑预约' : '新增预约' }}
              </a-button>
              <a-button
                @click="exportExcel" v-has="['exportAppoint']"
              >
                {{ '导出预约记录' }}
              </a-button>
            </a-col>
            <a-col>
              <a-select
                :value="String(value.year())"
                style="width: 90px; margin-right: 8px; font-size: 14px;"
                @change="val => { onChange(value.year(val)); }"
              >
                <a-select-option v-for="i in 10" :key="i" :value="String(moment().year() - 5 + i)">
                  {{ moment().year() - 5 + i }}
                </a-select-option>
              </a-select>
              <a-select
                :value="String(value.month())"
                style="width: 80px; font-size: 14px;"
                @change="val => { onChange(value.month(val)); }"
              >
                <a-select-option v-for="i in 12" :key="i-1" :value="String(i-1)">
                  {{ i }}月
                </a-select-option>
              </a-select>
            </a-col>
          </a-row>
        </div>
      </template>
    </a-calendar>
    <ScheduleFormModal ref="scheduleFormModal" :date="selectedDate" :url="url" @save="changeModelDate"/>

    <!-- 导出预约记录弹窗 -->
    <a-modal
      title="导出预约记录"
      :visible="exportDialogVisible"
      @ok="handleExport"
      @cancel="exportDialogVisible = false"
    >
      <a-form :form="form" layout="vertical">
        <a-form-item label="开始日期">
          <a-date-picker @change="onChangeStartDate" v-model="exportStartDate" placeholder="请选择开始日期" style="width: 100%" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="结束日期">
          <a-date-picker @change="onChangeEndDate" v-model="exportEndDate" placeholder="请选择结束日期" style="width: 100%" format="YYYY-MM-DD" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import {RyListMixin} from '@/ryweb'
import { exportExcel } from '@/utils/export.js'
import ScheduleFormModal from "./modules/ScheduleFormModal.vue";

export default {
  mixins: [RyListMixin, exportExcel],
  components: {ScheduleFormModal},
  data() {
    return {
      visible: false,
      loading: false,
      initQuery: false,
      confirmLoading: false,
      title: '理疗师排班管理',
      massagistId: '',
      massagistName: '',
      selectedDate: '',
      currentDate: moment(),
      scheduleFormVisible: false,
      scheduleList: [], // 存储所有排班数据
      currentScheduleData: [], // 当前选中日期的排班数据
      isDatePassed: false,
      form: this.$form.createForm(this),
      url: {
        list: this.$api.permission.appointment.appointment,
        add: this.$api.permission.appointment.insert,
        edit: this.$api.permission.appointment.update,
        exportFile: this.$api.permission.appointment.exportExcel,
        delete: this.$api.permission.appointment.deleteById
      },
      exportStartDate: null,
      exportEndDate: null,
      exportDialogVisible: false
    }
  },
  methods: {
    onSelectDate (date) {
      console.log('onSelectDate', date)
      this.selectedDate = date.format('YYYY-MM-DD')
      // 从已加载的数据中获取排班信息，不再调用接口
      this.loadScheduleFromList(this.selectedDate)
      // 更新当前日期，确保日历显示选中状态
      this.currentDate = date
    },
    // 从已加载的排班列表中获取指定日期的排班信息
    loadScheduleFromList (dateStr) {
      let schedule = this.scheduleList.filter(item => item.appointDate === dateStr)

      if (schedule) {
        this.currentScheduleData = schedule
      } else {
        // 如果没有找到排班数据，则设置为空对象
        this.currentScheduleData = []
      }
      console.log('currentScheduleData', this.currentScheduleData)
    },
    getListData (date) {
      const dateStr = date.format('YYYY-MM-DD')
      // 过滤日期和dateStr相同数据
      return this.scheduleList.filter(item => item.appointDate === dateStr)
    },
    onPanelChange (date, mode) {
      console.log('onPanelChange', date)
      // 更新当前日期
      this.currentDate = date
      // 清空选中日期，避免切换月份后仍然显示上个月的选中日期
      this.selectedDate = ''
      // 重新加载当前月份的排班数据
      this.loadAllSchedules()
    },
    changeModelDate () {
      this.loadAllSchedules()
      this.loadScheduleFromList(this.selectedDate)
    },
    // 加载当前月份的所有排班数据
    loadAllSchedules () {
      this.loading = true
      const startDate = moment(this.currentDate).startOf('month').format('YYYY-MM-DD')
      const endDate = moment(this.currentDate).endOf('month').format('YYYY-MM-DD')

      this.$post(this.url.list, {
          startDate: startDate,
          endDate: endDate
        }).then(res => {
          if (res.data) {
            this.scheduleList = res.data.records || []
            if (this.selectedDate !== '') {
              this.currentScheduleData = this.scheduleList.filter(item => item.appointDate === this.selectedDate)
            }
          }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleScheduleAction () {
      this.$refs.scheduleFormModal.show(this.currentScheduleData)
    },
    exportExcel () {
      this.exportDialogVisible = true
    },
    handleExport () {
      if (!this.exportStartDate || !this.exportEndDate) {
        this.$message.warning('请选择开始日期和结束日期')
        return
      }

      const startDate = moment(this.exportStartDate).format('YYYY-MM-DD')
      const endDate = moment(this.exportEndDate).format('YYYY-MM-DD')

      // 调用导出接口
      // window.open(`${this.url.exportFile}?startDate=${startDate}&endDate=${endDate}`)
      this.exportXlsNotDate(this.url.exportFile, {
        startDate: startDate,
        endDate: endDate
      }, startDate + '~' + endDate + '预约记录', false)
      this.exportDialogVisible = false
    },
    onChangeStartDate (date) {
      this.exportStartDate = date
    },
    onChangeEndDate (date) {
      this.exportEndDate = date
    }
  },
  computed: {
    hasScheduleForSelectedDate () {
      if (!this.selectedDate) return false
      return this.scheduleList.some(item => item.appointDate === this.selectedDate)
    }
  },
  created () {
    this.loadAllSchedules()
  }
}
</script>

<style lang="less">
.schedule-container {
  .calendar-header {
    padding: 8px 16px;
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-start;
  }

  .events {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .events .event {
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .schedule-cell {
    min-height: 32px;
  }

  .am-event {
    color: #1890ff;
  }

  .pm-event {
    color: #000000;
  }
}

:deep(.ant-fullcalendar-date) {
  min-height: 80px;
}
</style>
